package com.iary.application.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iary.application.TaokeService;
import com.iary.infrastructure.Page;
import com.iary.infrastructure.QueryCriteria;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeItemDetail;
import com.taobao.api.domain.TaobaokeShop;
import com.taobao.api.request.TaobaokeItemsConvertRequest;
import com.taobao.api.request.TaobaokeItemsDetailGetRequest;
import com.taobao.api.request.TaobaokeItemsGetRequest;
import com.taobao.api.request.TaobaokeShopsGetRequest;
import com.taobao.api.response.TaobaokeItemsConvertResponse;
import com.taobao.api.response.TaobaokeItemsDetailGetResponse;
import com.taobao.api.response.TaobaokeItemsGetResponse;
import com.taobao.api.response.TaobaokeShopsGetResponse;

public class TaokeServiceImpl implements TaokeService {

	private static final Logger log = LoggerFactory
			.getLogger(TaokeServiceImpl.class);

	private String appKey;
	private String appSecret;
	private String appUrl;
	private Long appPid;
	private String appNick;

	TaokeServiceImpl() {
	}

	public TaokeServiceImpl(String appKey, String appSecret, String appUrl,
			String appPid, String appNick) {
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.appUrl = appUrl;
		this.appPid = Long.valueOf(appPid);
		this.appNick = appNick;
	}

	@Override
	public TaobaokeItem getTbkItem(Long itemId) {
		TaobaokeItem result = null;
		if (itemId == null) {
			return result;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
		req.setPid(appPid);
		req.setNick(appNick);
		req.setNumIids(itemId.toString());
		try {
			TaobaokeItemsConvertResponse response = client.execute(req);
			if (response.isSuccess()) {
				if (response.getTotalResults() != null
						&& response.getTotalResults() > 0) {
					result = response.getTaobaokeItems().get(0);
				}
			} else {
				log.warn(
						"TaobaokeItemsConvertRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"TaobaokeItemsConvertRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (Exception e) {
			log.error("TaobaokeItemsConvertRequest error", e);
		}
		return result;
	}

	@Override
	public Page<TaobaokeItem> searchTbkItems(QueryCriteria criteria,
			Page<TaobaokeItem> page) {
		if (criteria == null) {
			return page;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
		req.setPid(appPid);
		req.setPageNo(Long.valueOf(page.getPageNo()));
		req.setPageSize(Long.valueOf(page.getPageSize()));
		if (StringUtils.isNotBlank(criteria.getKeyword())) {
			req.setKeyword(criteria.getKeyword());
		}
		if (criteria.getCid() != null && criteria.getCid() > 0) {
			req.setCid(criteria.getCid());
		}
		try {
			TaobaokeItemsGetResponse response = client.execute(req);
			if (response.isSuccess()) {
				if (response.getTotalResults() != null
						&& response.getTotalResults() > 0) {
					page.setTotalCount(response.getTotalResults());
					page.setResult(response.getTaobaokeItems());
				}
			} else {
				log.warn("TaobaokeItemsGetRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"TaobaokeItemsGetRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error("TaobaokeItemsGetRequest error", e);
		}
		return page;
	}

	@Override
	public List<TaobaokeShop> searchTbkShops(String keyword) {
		List<TaobaokeShop> result = new ArrayList<TaobaokeShop>();
		if (StringUtils.isBlank(keyword)) {
			return result;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		TaobaokeShopsGetRequest req = new TaobaokeShopsGetRequest();
		req.setFields("user_id,click_url,shop_title,commission_rate,seller_credit,shop_type,auction_count,total_auction");
		req.setKeyword(keyword);
		req.setPid(appPid);
		try {
			TaobaokeShopsGetResponse response = client.execute(req);
			if (response.isSuccess()) {
				if (response.getTotalResults() != null
						&& response.getTotalResults() > 0) {
					result = response.getTaobaokeShops();
				}
			} else {
				log.warn("TaobaokeShopsGetRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"TaobaokeShopsGetRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error("TaobaokeShopsGetRequest error", e);
		}
		return result;
	}

	@Override
	public TaobaokeItemDetail getTbkItemDetail(Long itemId) {
		TaobaokeItemDetail result = null;
		if (itemId == null) {
			return result;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		TaobaokeItemsDetailGetRequest req = new TaobaokeItemsDetailGetRequest();
		req.setFields("click_url,shop_click_url,seller_credit_score,num_iid,title,nick,desc,created,property_alias,cid,seller_cids,props,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,freight_payer,item_imgs,prop_imgs");
		req.setNumIids(itemId.toString());
		req.setNick(appNick);
		req.setPid(appPid);
		try {
			TaobaokeItemsDetailGetResponse response = client.execute(req);
			if (response.getTotalResults() != null
					&& response.getTotalResults() > 0) {
				result = response.getTaobaokeItemDetails().get(0);
			} else {
				log.warn(
						"TaobaokeItemsDetailGetRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"TaobaokeItemsDetailGetRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error("TaobaokeItemsDetailGetRequest error", e);
		}
		return result;
	}

	@Override
	public TaobaokeItemDetail getTbkItemLink(Long itemId) {
		TaobaokeItemDetail result = null;
		if (itemId == null) {
			return result;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		TaobaokeItemsDetailGetRequest req = new TaobaokeItemsDetailGetRequest();
		req.setFields("click_url,shop_click_url");
		req.setNumIids(itemId.toString());
		req.setNick(appNick);
		req.setPid(appPid);
		try {
			TaobaokeItemsDetailGetResponse response = client.execute(req);
			if (response.getTotalResults() != null
					&& response.getTotalResults() > 0) {
				result = response.getTaobaokeItemDetails().get(0);
			} else {
				log.warn(
						"TaobaokeItemsDetailGetRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"TaobaokeItemsDetailGetRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error("TaobaokeItemsDetailGetRequest error", e);
		}
		return result;
	}

}
